package com.sh.pangea.dsa.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.LargeValueFormatter;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.sh.lib.dsa.bean.AuthDetailInfo;
import com.sh.lib.dsa.bean.SummaryInfo;
import com.sh.lib.dsa.bean.UserWxDetailInfo;
import com.sh.lib.dsa.bean.analyzeresult.LinearItem;
import com.sh.lib.dsa.callback.ListListener;
import com.sh.lib.dsa.impl.AnalyzeManager;
import com.sh.pangea.dsa.R;
import com.sh.pangea.dsa.Utils.AnalyzeIntentUtil;
import com.sh.pangea.dsa.Utils.AnalyzeStringUtil;
import com.sh.pangea.dsa.Utils.CustomAnalyzeBoard;
import com.sh.pangea.dsa.Utils.FiltersUtil;
import com.sh.pangea.dsa.Utils.PieOtherAnalyzeBoard;
import com.sh.pangea.dsa.Utils.XYMarkerView;
import com.sh.pangea.dsa.adapter.LineChartAdapter;
import com.sh.pangea.dsa.adapter.PieChartAdapter;
import com.sh.pangea.dsa.adapter.TrendAuthDataListAdapter;
import com.sh.pangea.dsa.bean.AnalyzeResult;
import com.sh.pangea.dsa.bean.Level;
import com.sh.pangea.dsa.bean.MenuInfo;
import com.sh.pangea.dsa.observer.AnalyzePopWindowObservable;
import com.sh.pangea.dsa.observer.AnalyzePopWindowObserver;
import com.sh.pangea.dsa.observer.AnalyzeResultObservable;
import com.sh.pangea.dsa.observer.AnalyzeResultObserver;
import com.sh.pangea.dsa.view.CustomExpandableListView;
import com.sh.pangea.dsa.view.HospitalDetailsDataItem;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @675 无线认证
 */
public class TrendAuthDayActivity extends Activity implements AnalyzeResultObserver, AnalyzePopWindowObserver {
    /**
     * 筛选日期
     */
    @BindView(R.id.chart_filter_date)
    TextView chartFilterDate;
    /**
     * 其他筛选条件
     */
    @BindView(R.id.chart_filter_other)
    TextView chartFilterOther;
    /**
     * 图表名称
     */
    @BindView(R.id.chart_title)
    TextView chartTitle;
    /**
     * 折线图控件
     */
    @BindView(R.id.linar_chart_layout)
    LinearLayout linarChartLayout;
    /**
     * 柱状图控件
     */
    @BindView(R.id.bar_chart_layout)
    LinearLayout barChartLayout;
    /**
     * 饼状图控件
     */
    @BindView(R.id.pie_chart_layout)
    LinearLayout pieChartLayout;
    /**
     * 包裹主页面的线性布局
     */
    @BindView(R.id.trend_auth_linearlayout)
    LinearLayout trendAuthLinearlayout;
    /**
     * 滑动返回上一个界面
     */
//    @BindView(R.id.sildingFinishLayout)
//    SildingFinishLayout sildingFinishLayout;
    /**
     * 筛选UI控件
     */
    @BindView(R.id.filter_ui)
    RelativeLayout filterUi;
    /**
     * 显示昨日关键指标数据
     */
    @BindView(R.id.yest_day_info_layout)
    LinearLayout yestDayInfoLayout;
    /**
     * 放置昨日关键指标数据的控件
     */
    @BindView(R.id.trend_auth_yestday_relative)
    LinearLayout trendAuthYestdayRelative;
    /**
     * 标题栏文字
     */
    @BindView(R.id.title_layout_text)
    TextView titleLayoutText;
    /**
     * 放置数据列表的控件
     */
    @BindView(R.id.trend_auth_datalist)
    RecyclerView trendAuthDatalist;
    /**
     * 数据列表模块，在无数据的时候隐藏
     */
    @BindView(R.id.trend_auth_datalist_linear)
    LinearLayout trendAuthDatalistLinear;
    /**
     * 数据表控件
     */
    @BindView(R.id.trend_auth_data_expandable)
    CustomExpandableListView trendAuthDataExpandable;
    /**
     * 数据表父布局
     */
    @BindView(R.id.trend_auth_data_table_linear)
    LinearLayout trendAuthDataTableLinear;
    /**
     * 分享
     */
    @BindView(R.id.title_layout_share)
    ImageView titleLayoutShare;
    /**
     * 重置
     */
    @BindView(R.id.title_layout_reset)
    Button titleLayoutReset;
    /**
     * 菜单控件布局
     */
    @BindView(R.id.title_layout_menu)
    LinearLayout titleLayoutMenu;
    /**
     * 点击查看大图
     */
    @BindView(R.id.trend_auth_big_chart)
    ImageView trendAuthBigChart;
    /**
     * 图表和数据的分割线
     */
    @BindView(R.id.trend_auth_chart_divider)
    ImageView trendAuthChartDivider;
    // 子分类实例
    // T级
    private MenuInfo mParentPosition;
    // S级
    private MenuInfo mGroupPosition;
    // ABC级
    private MenuInfo mChildPosition;

    /**
     * ITEM ID
     */
    private String itemID = "";

    private Context mContext;
    private AnalyzeIntentUtil mAnalyzeIntentUtil;

    private final String TAG = "Main";
    /**
     * 折线图对象
     */
    private LineChart lineChart;
    /**
     * 柱状图对象
     */
    private BarChart barChart;
    /**
     * 饼状图对象
     */
    private PieChart pieChart;

    /**
     * Chart's LayoutParams
     */
    private ViewGroup.LayoutParams mLineChartLayout = null;

    private boolean has_K = false;
    private int levelValue = 0;
    private Entry mEntry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            // Translucent status bar
            window.setFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        setContentView(R.layout.activity_trend_auth_day);
        ButterKnife.bind(this);
        mContext = this;
        mAnalyzeIntentUtil = AnalyzeIntentUtil.getInstance(mContext);
        getIntentData();
        initView();
        initData();

        initListener();
        // 获取筛选数据 & 等待返回筛选View & 等待图表数据回调
        useFilterUtil();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AnalyzeResultObservable.getInstance().unregisterObserver(this);
        AnalyzePopWindowObservable.getInstance().unregisterObserver(this);
    }

    /**
     * 初始化控件
     */
    private void initView() {
        titleLayoutMenu.setVisibility(View.VISIBLE);

//        sildingFinishLayout.setOnSildingFinishListener(new SildingFinishLayout.OnSildingFinishListener() {
//            @Override
//            public void onSildingFinish() {
//                TrendAuthDayActivity.this.finish();
//            }
//        });
//        // touchView要设置到ListView上面
//        sildingFinishLayout.setTouchView(linarChartLayout);
//        sildingFinishLayout.setTouchView(barChartLayout);
//        sildingFinishLayout.setTouchView(pieChartLayout);
//        sildingFinishLayout.setTouchView(trendAuthLinearlayout);

        //分组展开
        trendAuthDataExpandable.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            public void onGroupExpand(int groupPosition) {
                setLineVisible(groupPosition, true);
            }
        });
        //分组关闭
        trendAuthDataExpandable.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
            public void onGroupCollapse(int groupPosition) {
                setLineVisible(groupPosition, false);
                if (isGroupExpanded()) {
                    isResetClickLineChart();
                } else {
                    Log.i(TAG, "onGroupCollapse: 二级列表没有都关闭");
                }
            }
        });
        //子项单击
        trendAuthDataExpandable.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            public boolean onChildClick(ExpandableListView arg0, View arg1,
                                        int groupPosition, int childPosition, long arg4) {
                switch (AnalyzeIntentUtil.getInstance(mContext).getIconType()) {
                    case AnalyzeIntentUtil.LINAR_CHART://折线图定位
                        if (mapEntry != null && mapEntry.size() > 0) {
                            ArrayList<Entry> entries = mapEntry.get(groupPosition);
                            if (entries != null && !entries.isEmpty()) {
                                Entry barEntry = entries.get(entries.size() - childPosition - 1);
                                if (barEntry != null) {
                                    Log.i(TAG, "onChildClick    barEntry.getX()  : " + barEntry.getX() + "     " + groupPosition);
                                    lineChart.highlightValue(barEntry.getX(), groupPosition, true);
                                } else {
                                    Log.i(TAG, "onItemClick: Entry is null");
                                }
                            }
                        } else {
                            Log.i(TAG, "onItemClick: entryList is null");
                        }
                        break;
                    case AnalyzeIntentUtil.BAR_CHART://柱状图定位
                        if (barEntriyList != null && barEntriyList.size() > 0) {
                            BarEntry barEntry = barEntriyList.get(childPosition);
                            if (barEntry != null) {
                                // TODO 设置选择项的名称
//                                setCurrentDataName(childPosition);
                                barChart.highlightValue(barEntry.getX(), 0, true);
                            } else {
                                Log.i(TAG, "onItemClick: barEntry is null");
                            }
                        } else {
                            Log.i(TAG, "onItemClick: barEntriyList is null");
                        }
                        break;
                    case AnalyzeIntentUtil.PIE_CHART://扇形图定位
                        if (entries_pie != null && entries_pie.size() > 0) {
                            pieChart.highlightValue(childPosition, 0, true);
                        }
                        showPieOther(childPosition);
                        break;
                    default:
                        Log.i(TAG, "onItemClick: 没有可匹配定位的图表");
                        break;
                }
                return false;
            }
        });
    }

    /**
     * 设置初始数据
     */
    private void initData() {
        // 标题名称
        titleLayoutText.setText(mParentPosition.getName());
        mLineChartLayout = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        // 注册观察者
        AnalyzeResultObservable.getInstance().registerObserver(this);
        AnalyzePopWindowObservable.getInstance().registerObserver(this);
    }

    /**
     * 注册监听
     */
    private void initListener() {
        FiltersUtil.getInstance(mContext).setFiltersUtilListener(mFiltersUtilListener);
    }

    /**
     * 返回
     **/
    @OnClick(R.id.title_layout_back)
    public void onBackClick(View view) {
        this.finish();
    }

    /**
     * 重置
     */
    @OnClick(R.id.title_layout_reset)
    public void onResetClick() {
        switch (AnalyzeIntentUtil.getInstance(mContext).getIconType()) {
            case AnalyzeIntentUtil.LINAR_CHART://重置折线图
                isResetClickLineChart();
                break;
            case AnalyzeIntentUtil.BAR_CHART://重置柱状图
                if (barChart != null) {
                    barChart.animateY(3000);
                    barChart.fitScreen();
                }
                break;
            case AnalyzeIntentUtil.PIE_CHART://重置扇形图
                if (pieChart != null) {
                    pieChart.animateY(3000);
                }
                break;
            default:
                Log.i(TAG, "handleMessage:重置化组件没有匹配项");
                break;
        }
    }

    /**
     * 分享
     */
    @OnClick(R.id.title_layout_share)
    public void onShareClick() {
        Bitmap bit = null;
        switch (AnalyzeIntentUtil.getInstance(mContext).getIconType()) {
            case AnalyzeIntentUtil.LINAR_CHART://折线图
                if (lineChart != null) {
                    lineChart.saveToGallery("thumbnail" /*+ System.currentTimeMillis()*/, 100);
                    bit = lineChart.getChartBitmap();
                }
                break;
            case AnalyzeIntentUtil.BAR_CHART://柱状图
                barChart.saveToGallery("thumbnail" /*+ System.currentTimeMillis()*/, 100);
                bit = barChart.getChartBitmap();
                break;
            case AnalyzeIntentUtil.PIE_CHART://扇形图
                pieChart.saveToGallery("thumbnail" /*+ System.currentTimeMillis()*/, 100);
                bit = pieChart.getChartBitmap();
                break;
            default:
                Log.i(TAG, "showIconType: 没有匹配的图表");
                break;
        }
        if (chartTitle != null) {
            ShareAction shareAction = new ShareAction(TrendAuthDayActivity.this);
            shareAction.withTitle(chartTitle.getText().toString());
            // TODO: 2016/12/26 暂时注释掉 ，需要修改
            shareAction.withText(/*mAnalyzeResult.getNameGraph()*/"");
            shareAction.withTargetUrl("http://www.skyworth-hightong.com");

            if (bit != null) {
                shareAction.withMedia(new UMImage(this.getApplicationContext(), bit));
            }
            shareAction.setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener).open();
        } else {
            Log.i(TAG, "onShareClick: mAnalyzeResult is null");
        }
    }

    private AnalyzeResult mAnalyzeResult = null;

    /**
     * 查看大图
     */
    @OnClick(R.id.trend_auth_big_chart)
    public void onBigChartClick() {
        Intent intent = new Intent(mContext, LineChartActivity2.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable("result", mAnalyzeResult);
        bundle.putString("name", mAnalyzeResult.getTitleGraph());
        intent.putExtras(bundle);
        mContext.startActivity(intent);
    }

    /**
     * 分享回调
     */
    private final UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA share_media) {
            Log.i(TAG, "分享返回值  onResult: " + share_media);
        }

        @Override
        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
            Log.i(TAG, "分享失败 onError: " + share_media);
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {
            Log.i(TAG, "取消分享  onCancel: " + share_media);
        }
    };

    /**
     * 获取筛选数据 & 等待返回筛选View & 等待图表数据回调
     */
    private void useFilterUtil() {
        // 启动筛选流程
        /**
         * 调用FiltersUtil，开始请求查询条件，并构建筛选节目UI，然后请求图表数据，以待返回结果。
         * 筛选UI通过FiltersUtilListener监听返回
         */
        if (mParentPosition != null && mGroupPosition != null && mChildPosition != null) {
            FiltersUtil.getInstance(mContext).launch(mParentPosition, mGroupPosition, mChildPosition);
        } else {
            AnalyzeResultObservable.getInstance().onAnalyzeResult(-200, "接到的三个实体对象为空", null);
        }
    }

    /**
     * 获取传过来的数据
     */
    private void getIntentData() {
        Intent intent = this.getIntent();
        mParentPosition = (MenuInfo) intent.getSerializableExtra("parentInfo");
        mGroupPosition = (MenuInfo) intent.getSerializableExtra("groupInfo");
        mChildPosition = (MenuInfo) intent.getSerializableExtra("childInfo");

        if (mParentPosition != null && mGroupPosition != null && mChildPosition != null) {
            itemID = mParentPosition.getId() + mGroupPosition.getId() + mChildPosition.getId();
        }
    }

    /**
     * 获取昨日关键指标数据
     */
    private void getYestDayInfo() {
        mAnalyzeIntentUtil.callQueryYestDayInfoInterface(itemID, yestDayInfoListListener);
    }

    /**
     * 获取数据列表
     */
    private void getDateList() {
        mAnalyzeIntentUtil.callQueryDateListInterface(itemID, dateListListListener);
    }

    /**
     * 昨日关键指标数据回调
     */
    private ListListener yestDayInfoListListener = new ListListener<SummaryInfo>() {
        @Override
        public void onSuccess(List<SummaryInfo> list) {
            //  填充昨日数据
            Log.i("Main", "填充昨日数据   onSuccess()   list：" + list.size());
            if (list != null && !list.isEmpty()) {
                trendAuthYestdayRelative.setVisibility(View.VISIBLE);
                addYestDayView(list);
            } else {
                trendAuthYestdayRelative.setVisibility(View.GONE);
            }
        }

        @Override
        public void onPrepare(String s) {

        }

        @Override
        public void onFail(int i, String s) {
            trendAuthYestdayRelative.setVisibility(View.GONE);
        }
    };

    private String cancleDateList = null;
    /**
     * 数据列表回调
     */
    private ListListener dateListListListener = new ListListener() {
        @Override
        public void onSuccess(List list) {
            // 填充数据列表数据
            Log.i("Main", "数据列表回调   onSuccess()   list：" + list.size());
            if (!childDataMap.isEmpty() || !groupTime.isEmpty()) {
                groupTime.clear();
                childDataMap.clear();
            }

            if (list != null && !list.isEmpty()) {
                trendAuthDatalistLinear.setVisibility(View.VISIBLE);
                Object object = list.get(0);
                //
                if (object instanceof AuthDetailInfo) {
                    // 无线认证总览数据列表
                    parserAuthDetaList(list);
                    Log.i("Main", "数据列表回调   无线认证总览数据列表");
                } else if (object instanceof UserWxDetailInfo) {
                    // 公众号用户总览数据列表
                    Log.i("Main", "数据列表回调   公众号用户总览数据列表");
                    parserUserWxDetaList(list);
                }
                TrendAuthDataListAdapter mTrendAuthDataListAdapter = new TrendAuthDataListAdapter(groupTime, childDataMap, mContext);
                trendAuthDatalist.setAdapter(mTrendAuthDataListAdapter);
            }

        }

        @Override
        public void onPrepare(String s) {
            if (cancleDateList != null) {
                AnalyzeManager.instence().cancelReq(cancleDateList);
            }
            cancleDateList = s;
        }

        @Override
        public void onFail(int i, String s) {
            Log.i("Main", "数据列表回调   onFail()  i:" + i + "   error:" + s);
//            trendAuthDatalistLinear.setVisibility(View.GONE);
        }
    };

    private FiltersUtil.FiltersUtilListener mFiltersUtilListener = new FiltersUtil.FiltersUtilListener() {

        @Override
        public void addFilterView(View filterView) {
            // 加筛选View
            if (filterView != null) {
                if (filterUi.getChildCount() >= 1)
                    filterUi.removeViewAt(0);
                filterUi.addView(filterView, 0);
            }
        }

        @Override
        public void commitFilters(String filterString, String day, String week) {
            // 获取昨日关键指标数据
            getYestDayInfo();
            // 获取数据列表
            getDateList();

            // 显示所选筛选条件
            if (week == null) {
                week = "";
            }
            if (day == null) {
                day = "";
            }
            if (TextUtils.isEmpty(week) && TextUtils.isEmpty(day)) {
                chartFilterDate.setVisibility(View.GONE);
            } else {
                chartFilterDate.setVisibility(View.VISIBLE);
                chartFilterDate.setText("筛选日期 ：" + day + "  " + week);
            }

            if (filterString == null || TextUtils.isEmpty(filterString)) {
                chartFilterOther.setVisibility(View.GONE);
            } else {
                chartFilterOther.setVisibility(View.VISIBLE);
                chartFilterOther.setText("其他条件 ：" + filterString);
            }
        }
    };

    /**
     * 数据列表返回数据的日期集合
     */
    private ArrayList<String> groupTime = new ArrayList<>();
    /**
     * 数据列表返回数据的集合
     * key:日期   value:其他数据
     */
    private Map<String, List<String>> childDataMap = new HashMap<>();

    /**
     * 把无线认证总览数据列表数据解析成按日期分的map。
     *
     * @param list AuthDetailInfo列表
     */
    private void parserAuthDetaList(List<AuthDetailInfo> list) {
        if (!childDataMap.isEmpty() || !groupTime.isEmpty()) {
            groupTime.clear();
            childDataMap.clear();
        }

        for (int i = 0; i < list.size(); i++) {
            AuthDetailInfo authDetailInfo = list.get(i);
            String playDay = authDetailInfo.getPlayDay();
            groupTime.add(playDay);
            List<String> childData = new ArrayList<>();
            childData.add("放行次数:" + authDetailInfo.getNumsSuccess());
            childData.add("放行设备数:" + authDetailInfo.getNumsSuccessDev());
            childData.add("免认证次数:" + authDetailInfo.getNumsFree());
            childData.add("免认证设备数:" + authDetailInfo.getNumsFreeDev());
            childData.add("认证次数:" + authDetailInfo.getNumsTotal());
            childData.add("认证设备数:" + authDetailInfo.getNumsTotalDev());
            childData.add("认证成功次数比率:" + authDetailInfo.getRatePv());
            childData.add("认证成功设备比率:" + authDetailInfo.getRateUv());
            childData.add("人均放行次数:" + authDetailInfo.getPerPv());
            childData.add("人均认证次数:" + authDetailInfo.getPerUv());
            childData.add("新增设备数:" + authDetailInfo.getNumsAddDev());
            int numsAddUser = authDetailInfo.getNumsAddUser();
            if (numsAddUser != 0) {
                childData.add("新增用户数:" + authDetailInfo.getNumsAddUser());
            }

            childDataMap.put(playDay, childData);
        }

    }

    /**
     * 公众号用户总览数据列表数据解析成按日期分的map。
     *
     * @param list UserWxDetailInfo列表
     */
    private void parserUserWxDetaList(List<UserWxDetailInfo> list) {
        if (!childDataMap.isEmpty() || !groupTime.isEmpty()) {
            groupTime.clear();
            childDataMap.clear();
        }

        for (int i = 0; i < list.size(); i++) {
            UserWxDetailInfo userWxDetailInfo = list.get(i);
            String playDay = userWxDetailInfo.getPlayDay();
            groupTime.add(playDay);
            List<String> childData = new ArrayList<>();
            childData.add("新关注人数:" + userWxDetailInfo.getNumsAttentionUser());
            childData.add("累计关注人数:" + userWxDetailInfo.getNumsAttentionUserSum());
            childData.add("取消关注人数:" + userWxDetailInfo.getNumsGiveupUser());
            childData.add("净增关注人数:" + userWxDetailInfo.getNumsNetUser());

            childDataMap.put(playDay, childData);
        }

    }

    /**
     * 根据昨日关键指标数据，添加昨日数据的UI
     *
     * @param list
     */
    private void addYestDayView(List<SummaryInfo> list) {
        yestDayInfoLayout.removeAllViews();
        for (int i = 0; i < list.size(); i++) {
            SummaryInfo summaryInfo = list.get(i);
            HospitalDetailsDataItem item = new HospitalDetailsDataItem(this);
            item.update(summaryInfo);
            yestDayInfoLayout.addView(item);
        }
    }

    private CustomAnalyzeBoard mCustomAnalyzeBoard = null;

    @Override
    public void onAnalyzePopWindow(int code, String error, AnalyzeResult analyzeResult) {
        if (mCustomAnalyzeBoard != null && mCustomAnalyzeBoard.isShowing()) {
            mCustomAnalyzeBoard.dismiss();
        }
        if (!TrendAuthDayActivity.this.isFinishing()) {
            //初始化popWindow
            mCustomAnalyzeBoard = new CustomAnalyzeBoard(mContext, analyzeResult);
            mCustomAnalyzeBoard.showAtLocation(TrendAuthDayActivity.this.getWindow().getDecorView(), Gravity.CENTER, 0, 0);
            mCustomAnalyzeBoard.setOutsideTouchable(true);  //设置点击屏幕其它地方弹出框消失
        }
    }

    /**
     * 折线图或柱状图图表接口回调
     *
     * @param code
     * @param error
     * @param analyzeResult
     */
    @Override
    public void onAnalyzeResult(int code, String error, AnalyzeResult analyzeResult) {
        Log.i("Main", "图表接口回调  onAnalyzeResult");
        initChart();

        if (analyzeResult != null) {
            trendAuthChartDivider.setVisibility(View.VISIBLE);
            mAnalyzeResult = analyzeResult;
            String titleGraph = analyzeResult.getTitleGraph();

            if (titleGraph != null && !TextUtils.isEmpty(titleGraph)) {
                chartTitle.setVisibility(View.VISIBLE);
            } else {
                chartTitle.setVisibility(View.GONE);
                titleGraph = "";
            }
            chartTitle.setText(titleGraph);

            getXString(analyzeResult.getxForGraph());
            showIconType(analyzeResult.getyForGraph(), titleGraph);
            setXDataList();
        }
    }

    /**
     * 初始化图表
     */
    private void initChart() {
        trendAuthBigChart.setVisibility(View.VISIBLE);
        switch (mChildPosition.getChartType()) {
            case AnalyzeIntentUtil.LINAR_CHART://初始化折线组件
                linarChartLayout.removeAllViews();
                lineChart = new LineChart(mContext);
                lineChart.setLayoutParams(mLineChartLayout);
                setLineChart(lineChart);
                linarChartLayout.addView(lineChart);
                break;
            case AnalyzeIntentUtil.BAR_CHART://初始化柱状图组件
                barChartLayout.removeAllViews();
                barChart = new BarChart(mContext);
                barChart.setLayoutParams(mLineChartLayout);
                setBarChart(barChart);
                barChartLayout.addView(barChart);
                isShowPopWind();
                break;
            case AnalyzeIntentUtil.PIE_CHART://初始化扇形图
                pieChartLayout.removeAllViews();
                pieChart = new PieChart(mContext);
                pieChart.setLayoutParams(mLineChartLayout);
                setPieChart(pieChart);
                pieChartLayout.addView(pieChart);
                break;
            default:
                Log.i(TAG, "handleMessage: 初始化组件没有匹配项");
                break;
        }
    }

    private void setLineChart(LineChart lineChart) {
        //此方法设置为false时图像拉大后，用手指不能左右上下拖动
        lineChart.setDragEnabled(true);
        //去掉图标的标志
        lineChart.getDescription().setEnabled(false);
        //禁止水平方向拖拽
        lineChart.setScaleXEnabled(true);
        //禁止垂直方向拖拽
        lineChart.setScaleYEnabled(false);
        //画图标的边框
        lineChart.setDrawBorders(true);
        //设置图标边框的线的宽度
        //lineChart.setBorderWidth(2f);
        //设置数据为空时显示的描述文字
        lineChart.setNoDataText("暂时没有数据！");
        //设置数据为空时显示的描述文字的颜色
        lineChart.setNoDataTextColor(getResources().getColor(R.color.colorPrimaryDark));
        //设置图表的背景颜色 不知道为什么不起作用
        //lineChart.setGridBackgroundColor(getResources().getColor(R.color.colorSub));
        //
        //lineChart.getYChartMin(false);

        // 设置Legend启用或禁用
        Legend legend = lineChart.getLegend();
        legend.setEnabled(true);
        legend.setTextSize(12);
        legend.setTextColor(getResources().getColor(R.color.colorTextMinor));


        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f); // only intervals of 1 day
        xAxis.setLabelCount(7);
        xAxis.setValueFormatter(mIAxisValueFormatter_X);
        //设置x轴字体显示角度,即X轴上文字呈现斜着显示
        xAxis.setLabelRotationAngle(0);
        //设置X轴的位置TOP, BOTTOM, BOTH_SIDED, TOP_INSIDE, BOTTOM_INSIDE
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);

        YAxis leftAxis = lineChart.getAxisLeft();
        leftAxis.setInverted(false);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
//        leftAxis.setGranularityEnabled(true);
//        leftAxis.setGridColor(10);
//        leftAxis.setDrawLimitLinesBehindData(true);
//        leftAxis.setDrawZeroLine(false);
        //leftAxis.setAxisMaximum(300f);
        leftAxis.setValueFormatter(mIAxisValueFormatter_Y);
        YAxis rightAxis = lineChart.getAxisRight();
        rightAxis.setEnabled(true);
        rightAxis.setInverted(false);
        rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        rightAxis.setValueFormatter(mIAxisValueFormatter_Y_right);

        // get the legend (only possible after setting data)
        Legend l = lineChart.getLegend();
        // modify the legend ...
        l.setForm(Legend.LegendForm.LINE);
        // dont forget to refresh the drawing
        lineChart.invalidate();
        lineChart.animateY(3000);
//        //点击显示数据组件
//        XYMarkerView mv = new XYMarkerView(this, mIAxisValueFormatter_X);
//        mv.setChartView(lineChart); // For bounds control
//        lineChart.setMarker(mv); // Set the marker to the chart

    }


    private void setBarChart(BarChart barChart) {
        //Set this to true to enable dragging (moving the chart with the finger) for the chart (this does not effect scaling).
        //此方法设置为false时图像拉大后，用手指不能左右上下拖动
        barChart.setDragEnabled(true);
        barChart.setDrawBarShadow(false);
        barChart.setDrawValueAboveBar(false);
        barChart.getDescription().setEnabled(false);
        //禁止水平方向拖拽
        barChart.setScaleXEnabled(true);
        //禁止垂直方向拖拽
        barChart.setScaleYEnabled(false);
        //取消双击放大功能
        barChart.setDoubleTapToZoomEnabled(false);
        //画图标的边框
        barChart.setDrawBorders(true);
        //设置图标边框的线的宽度
        //barChart.setBorderWidth(2f);
        barChart.animateY(3000);
        // if more than 60 entries are displayed in the chart, no values will be drawn
        barChart.setMaxVisibleValueCount(60);
        // scaling can now only be done on x- and y-axis separately
//        barChart.setPinchZoom(false);
        barChart.setDrawGridBackground(false);
        barChart.setFitBars(true);

        //设置数据为空时显示的描述文字
        barChart.setNoDataText("暂时没有数据！");
        //设置数据为空时显示的描述文字的颜色
        barChart.setNoDataTextColor(getResources().getColor(R.color.colorPrimaryDark));
        //设置图表的背景颜色  不知道为什么不起作用
        //barChart.setGridBackgroundColor(getResources().getColor(R.color.colorSub));

        // 设置Legend启用或禁用
        Legend legend = barChart.getLegend();
        legend.setEnabled(false);
        legend.setTextColor(getResources().getColor(R.color.colorAccent));
        legend.setWordWrapEnabled(true);

        XAxis xAxisc = barChart.getXAxis();
        xAxisc.setPosition(XAxis.XAxisPosition.BOTTOM);
//        xAxisc.setDrawGridLines(false);
        // only intervals of 1 day  即：每柱只显示一个值
        xAxisc.setGranularity(1f);
        xAxisc.setLabelCount(7);
        xAxisc.setValueFormatter(mIAxisValueFormatter_X);
//        xAxisc.setAxisMinimum(0f);
        xAxisc.setDrawAxisLine(true);
        //设置x轴字体显示角度,即X轴上文字呈现斜着显示 -90
        xAxisc.setLabelRotationAngle(0);
        //设置X轴的位置TOP, BOTTOM, BOTH_SIDED, TOP_INSIDE, BOTTOM_INSIDE
        xAxisc.setPosition(XAxis.XAxisPosition.BOTTOM);
        //设置x轴的颜色
        xAxisc.setAxisLineColor(getResources().getColor(R.color.colorAccent));
//
        YAxis leftAxisc = barChart.getAxisLeft();
        leftAxisc.setLabelCount(8, false);
        leftAxisc.setValueFormatter(mIAxisValueFormatter_Y);
//        leftAxisc.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxisc.setSpaceTop(15f);
        leftAxisc.setAxisMinimum(0f);

        YAxis rightAxisc = barChart.getAxisRight();
        //设置右边Y轴是否显示数据
        rightAxisc.setEnabled(false);
        rightAxisc.setSpaceTop(15f);
        rightAxisc.setValueFormatter(mIAxisValueFormatter_Y);
        rightAxisc.setAxisMinimum(0f);

        Legend lc = barChart.getLegend();
        lc.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        lc.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        lc.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        lc.setDrawInside(false);
        lc.setForm(Legend.LegendForm.SQUARE);
        lc.setFormSize(9f);
        lc.setTextSize(6f);
        lc.setXEntrySpace(4f);

        //点击没柱显示数据
        XYMarkerView mv = new XYMarkerView(this, mIAxisValueFormatter_X);
        mv.setChartView(barChart); // For bounds control
        barChart.setMarker(mv); // Set the marker to the chart
        barChart.setOnChartValueSelectedListener(mOnChartValueSelectedListener);
    }

    private void setPieChart(PieChart pieChart) {
        //用自带的百分比算法
        pieChart.setUsePercentValues(true);
        pieChart.getDescription().setEnabled(false);
        //设置整个饼状图是空心还是实心
        pieChart.setDrawHoleEnabled(false);
        pieChart.setExtraOffsets(20f, 5.f, 20f, 5.f);
        //图标log显示在中心
        pieChart.setDrawCenterText(false);
        /**
         *触摸是否可以旋转以及松手后旋转的度数
         */
        pieChart.setRotationAngle(300);
        // enable rotation of the chart by touch
        pieChart.setRotationEnabled(true);
        pieChart.setHighlightPerTapEnabled(true);
        //饼形图上是否显示每个模块的X轴的值
        pieChart.setDrawEntryLabels(false);
        pieChart.animateX(1000);
        //设置数据为空时显示的描述文字
        pieChart.setNoDataText("暂时没有数据！");
        Legend l = pieChart.getLegend();
//        pieChart.setHoleColor();
//        l.setDrawInside(true);
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(true);
        l.setEnabled(true);
    }

    /**
     * 响应点击柱状图的每个小柱子，发消息弹框
     **/
    private final OnChartValueSelectedListener mOnChartValueSelectedListener = new OnChartValueSelectedListener() {
        @Override
        public void onValueSelected(Entry e, Highlight h) {
            Log.i(TAG, "onValueSelected:  " + e + "   " + h);
            if (isShowPopwind) {
                mEntry = e;
                if (mEntry != null) {
                    float x = mEntry.getX();
                    String formattedValue = xForGraph.get((int) x);
                    String format = mFormat.format(mEntry.getY());
                    AnalyzeIntentUtil.getInstance(mContext).setMedicalName(formattedValue);
                    AnalyzeIntentUtil.getInstance(mContext).callSmallLineChart(itemID);
                } else {
                    Log.i(TAG, "handleMessage: mEntry is null ");
                }
            } else {
                float x = e.getX();
                // TODO setCurrentDataName
//                setCurrentDataName((int) x);
                Log.i(TAG, "onValueSelected: 日排行榜不需要弹框    " + x);
            }
        }

        @Override
        public void onNothingSelected() {
            Log.i("TGH", "onNothingSelected: ");
        }
    };

    private final IAxisValueFormatter mIAxisValueFormatter_X = new IAxisValueFormatter() {

        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            String a = "";
            switch (AnalyzeIntentUtil.getInstance(mContext).getIconType()) {
                case AnalyzeIntentUtil.BAR_CHART://柱状图
                    a = ((int) value) + 1 + "";
                    break;
                case AnalyzeIntentUtil.LINAR_CHART://折线图
                    if (xForGraph != null) {
                        a = xForGraph.get(Math.min(Math.max((int) value, 0), xForGraph.size() - 1));
                    }
                    break;
                case AnalyzeIntentUtil.PIE_CHART://扇形图
                    break;
                default:
                    break;
            }
            return a;
        }

        @Override
        public int getDecimalDigits() {
            return 0;
        }
    };

    private final DecimalFormat mFormat = new DecimalFormat("###,###,###,##0");
    private final IAxisValueFormatter mIAxisValueFormatter_Y = new IAxisValueFormatter() {
        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            String s;
            if (mFormat != null) {
                s = mFormat.format(value);
            } else {
                s = null;
            }
            return s;
        }

        @Override
        public int getDecimalDigits() {
            return 0;
        }
    };

    private final IAxisValueFormatter mIAxisValueFormatter_Y_right = new IAxisValueFormatter() {
        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            String s;
            if (mFormat != null) {
                if (has_K) {
                    int l = levelValue / 1000;
                    String s1 = String.valueOf(l);
                    s1 = s1.substring(1);
                    s = mFormat.format(value) + s1 + " K";
                } else {
                    s = mFormat.format(value);
                }
            } else {
                s = null;
            }
            return s;
        }

        @Override
        public int getDecimalDigits() {
            return 0;
        }
    };

    /**
     * 点击柱状图是否弹起popwind窗口
     **/
    private boolean isShowPopwind = false;

    private void isShowPopWind() {
        if (mChildPosition.getChartType().equals("B") && mChildPosition.getDateSelect().equals("999")) {
            isShowPopwind = true;
        }
    }

    private List<String> xForGraph = new ArrayList<>();

    /**
     * 获取X轴数据
     **/
    private void getXString(List<String> xList) {
        if (xList != null && xList.size() > 0) {
            xForGraph = xList;
        } else {
            Log.i(TAG, "getXString: xList is null");
            xForGraph = null;
        }
    }

    private void showIconType(List<LinearItem> linearItems, String nameGraph) {
        if (linearItems != null && linearItems.size() > 0) {
            Log.i("TGH", "showIconType  : " + linearItems);
//            generateDataLine(linearItems, nameGraph);
            switch (AnalyzeIntentUtil.getInstance(mContext).getIconType()) {
                case AnalyzeIntentUtil.LINAR_CHART://折线图
//                    generateDataLine(linearItems, nameGraph);
                    setNeighborhoodComparison(linearItems, nameGraph);
                    barChartLayout.setVisibility(View.GONE);
                    pieChartLayout.setVisibility(View.GONE);
                    linarChartLayout.setVisibility(View.VISIBLE);
                    break;
                case AnalyzeIntentUtil.BAR_CHART://柱状图
                    generateDataBar(linearItems, nameGraph);
                    linarChartLayout.setVisibility(View.GONE);
                    pieChartLayout.setVisibility(View.GONE);
                    barChartLayout.setVisibility(View.VISIBLE);
                    break;
                case AnalyzeIntentUtil.PIE_CHART://扇形图
                    linearItems = getManagePieDate(linearItems);
                    generateDataPie(linearItems);
                    linarChartLayout.setVisibility(View.GONE);
                    barChartLayout.setVisibility(View.GONE);
                    pieChartLayout.setVisibility(View.VISIBLE);
                    break;
                default:
                    Log.i(TAG, "showIconType: 没有匹配的图表");
                    break;
            }
        } else {
            Log.i(TAG, "showIconType: linearItems is null");
        }
    }

    private void setXDataList() {
        if (xForGraph != null && xForGraph.size() > 0) {
            LineChartAdapter mTvChannelAdapter = new LineChartAdapter(mContext, setInvertedOrderYForGraph(mMonthsValues), setInvertedOrderXForGraph(xForGraph));
            trendAuthDataExpandable.setAdapter(mTvChannelAdapter);
            trendAuthDataExpandable.setGroupIndicator(getResources().getDrawable(R.drawable.expandablelistview));
            if (trendAuthDataExpandable != null && mTvChannelAdapter.getGroupCount() > 0) {
                // 展开全部子项
//                for (int i = 0; i < mTvChannelAdapter.getGroupCount(); i++) {
//                    trendAuthDataExpandable.expandGroup(i);
//                }
            }
            if (xForGraph.size() > 0) {
                trendAuthDataExpandable.setVisibility(View.VISIBLE);
                trendAuthDataTableLinear.setVisibility(View.VISIBLE);
            } else {
                trendAuthDataTableLinear.setVisibility(View.GONE);
                trendAuthDataExpandable.setVisibility(View.INVISIBLE);
//                setNoChartData();
            }
        } else {
            Log.i(TAG, "handleMessage  onSuccess  xForGraph is null ");
            switch (AnalyzeIntentUtil.getInstance(mContext).getIconType()) {
                case AnalyzeIntentUtil.PIE_CHART://初始化扇形图
                    if (mMonthsValues != null && mMonthsValues.size() > 0) {
                        PieChartAdapter mPieChartAdapter = new PieChartAdapter(mContext, mMonthsValues);
                        trendAuthDataExpandable.setAdapter(mPieChartAdapter);
                        trendAuthDataExpandable.setGroupIndicator(getResources().getDrawable(R.drawable.expandablelistview));
                        if (trendAuthDataExpandable != null && mPieChartAdapter.getGroupCount() > 0) {
                            for (int i = 0; i < mPieChartAdapter.getGroupCount(); i++) {
                                trendAuthDataExpandable.expandGroup(i);
                            }
                        }
                        trendAuthDataTableLinear.setVisibility(View.VISIBLE);
                        trendAuthDataExpandable.setVisibility(View.VISIBLE);
                    } else {
                        trendAuthDataTableLinear.setVisibility(View.GONE);
                        trendAuthDataExpandable.setVisibility(View.INVISIBLE);
//                        setNoChartData();
                    }
                    break;
                default:
                    trendAuthDataTableLinear.setVisibility(View.GONE);
                    trendAuthDataExpandable.setVisibility(View.INVISIBLE);
//                    setNoChartData();
                    Log.i(TAG, "handleMessage: onSuccess  折线图或者柱状图X轴为空");
                    break;
            }
        }
    }

    private List<Level> mLevel = null;

    /**
     * 获取最大值
     **/
    private void setNeighborhoodComparison(List<LinearItem> linearItems, String nameGraph) {
        Comparator comp = new Comparator() {
            public int compare(Object o1, Object o2) {
                Integer p1 = (Integer) o1;
                Integer p2 = (Integer) o2;
                if (p1 < p2)
                    return -1;
                else if (p1 == p2)
                    return 0;
                else if (p1 > p2)
                    return 1;
                return 0;
            }
        };

        List<Integer> maxDataList = new ArrayList<>();
        mLevel = new ArrayList<>();
        List<Integer> data = null;
        LinearItem linearItem = null;
        for (int a = 0; a < linearItems.size(); a++) {
            linearItem = linearItems.get(a);
            data = linearItem.getData();
            if (data != null) {
                Integer max = (Integer) Collections.max(data, comp);
                Integer min = (Integer) Collections.min(data, comp);
                String name = linearItem.getName();
                mLevel.add(new Level(max, name, data));
                maxDataList.add(a, max);
            }
        }

        if (maxDataList.size() > 0) {
            Integer min = (Integer) Collections.min(maxDataList, comp);
            for (int m = 0; m < mLevel.size(); m++) {
                Level l = mLevel.get(m);
                l.setMin(min);
            }
        }
        generateDataLine(linearItems, mLevel);
    }

    public void generateDataLine(List<LinearItem> linearItems, String nameGraph) {
        if (linearItems != null && linearItems.size() > 0) {
            ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
            LineDataSet set1;
            for (int a = 0; a < linearItems.size(); a++) {
                ArrayList<Entry> yVals1 = new ArrayList<Entry>();
                LinearItem linearItem = linearItems.get(a);
                String name = linearItem.getName();
                List<Integer> data = linearItem.getData();
                for (int i = 0; i < data.size(); i++) {
                    int i1 = data.get(i);
                    if (i1 > 1000) {
                        has_K = true;
                    }
                    Entry entry = new Entry(i, i1);
                    entry.setName(name);
                    yVals1.add(entry);
                }
//                Log.i("Main", "generateDataLine()   lineChart==null:" + (lineChart == null) + "   lineChart.getData()==null:" + (lineChart.getData() == null));
                if (lineChart.getData() != null &&
                        lineChart.getData().getDataSetCount() > 0) {
                    set1 = (LineDataSet) lineChart.getData().getDataSetByIndex(a);
                    set1.setValues(yVals1);
                } else {
                    set1 = new LineDataSet(yVals1, nameGraph);
                    if (a % 2 == 0) {
                        Log.i("TGH", "setData: " + a);
                        set1.setAxisDependency(YAxis.AxisDependency.LEFT);
                    } else {
                        set1.setAxisDependency(YAxis.AxisDependency.RIGHT);

                    }
                    int number = AnalyzeStringUtil.getInstance().getNumber(a);
                    set1.setColor(AnalyzeStringUtil.COLORS[number]);
                    set1.setFillColor(AnalyzeStringUtil.COLORS[number]);
                    set1.setAxisDependency(YAxis.AxisDependency.LEFT);
                    set1.setCircleColor(AnalyzeStringUtil.COLORS[number]);
                    set1.setLineWidth(2f);
                    set1.setCircleRadius(3f);
                    set1.setFillAlpha(65);

                    set1.setHighLightColor(Color.rgb(244, 117, 117));
                    set1.setDrawCircleHole(false);
                    set1.setDrawValues(false);
                    dataSets.add(set1); // add the datasets
                }

            }
            if (lineChart.getData() != null &&
                    lineChart.getData().getDataSetCount() > 0) {
                lineChart.getData().notifyDataChanged();
                lineChart.notifyDataSetChanged();
            } else {
                // create a data object with the datasets
                LineData data = new LineData(dataSets);
                data.setValueTextColor(Color.RED);
                data.setValueTextSize(9f);
                data.setValueFormatter(new LargeValueFormatter());
                // set data
                lineChart.setData(data);
            }
        } else {
            Log.i(TAG, "generateDataLine: linearItems list is null ");
        }

    }

    private List<LinearItem> mMonthsValues = new ArrayList<>();
    Map<Integer, ArrayList<Entry>> mapEntry = new HashMap<Integer, ArrayList<Entry>>();

    /**
     * generates a random ChartData object with just one DataSet
     */
    public void generateDataLine(List<LinearItem> linearItems, List<Level> mLevel) {
        if (linearItems != null && linearItems.size() > 0) {
            ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
            LineDataSet set1;
            mMonthsValues = linearItems;
            for (int a = 0; a < linearItems.size(); a++) {
                ArrayList<Entry> yVals1 = new ArrayList<Entry>();
                LinearItem linearItem = linearItems.get(a);
                String name = linearItem.getName();
                List<Integer> data = linearItem.getData();
                if (data != null) {
                    for (int i = 0; i < data.size(); i++) {
                        float i1 = data.get(i);
                        int levelByName = getLevelByName(mLevel, name);
                        if (i1 > 1000) {
                            has_K = true;
                            levelValue = levelByName;
                        }
                        i1 = i1 / levelByName;
                        Entry entry = new Entry(i, i1);
                        entry.setLevel(levelByName);
                        entry.setName(name);
                        yVals1.add(entry);
                    }
                    mapEntry.put(a, yVals1);
                    if (lineChart.getData() != null &&
                            lineChart.getData().getDataSetCount() > 0) {
                        set1 = (LineDataSet) lineChart.getData().getDataSetByIndex(a);
                        set1.setValues(yVals1);
                    } else {
                        set1 = new LineDataSet(yVals1, name);
                        if (a % 2 == 0) {
                            Log.i("TGH", "setData: " + a);
                            set1.setAxisDependency(YAxis.AxisDependency.LEFT);
                        } else {
                            set1.setAxisDependency(YAxis.AxisDependency.RIGHT);

                        }
                        int number = AnalyzeStringUtil.getInstance().getNumber(a);
                        set1.setColor(AnalyzeStringUtil.getInstance().COLORS[number]);
                        set1.setFillColor(AnalyzeStringUtil.getInstance().COLORS[number]);
                        set1.setAxisDependency(YAxis.AxisDependency.LEFT);
                        set1.setCircleColor(AnalyzeStringUtil.getInstance().COLORS[number]);
                        set1.setLineWidth(2f);
                        set1.setCircleRadius(3f);
                        set1.setFillAlpha(65);

                        set1.setHighLightColor(Color.rgb(244, 117, 117));
                        set1.setDrawCircleHole(false);
                        set1.setDrawValues(false);
                        dataSets.add(set1); // add the datasets
                    }
                }
            }
            if (lineChart.getData() != null &&
                    lineChart.getData().getDataSetCount() > 0) {
                lineChart.getData().notifyDataChanged();
                lineChart.notifyDataSetChanged();
            } else {
                // create a data object with the datasets
                LineData data = new LineData(dataSets);
                data.setValueTextColor(Color.RED);
                data.setValueTextSize(9f);
                data.setValueFormatter(new LargeValueFormatter());
                // set data
                lineChart.setData(data);
            }
        } else {
            Log.i(TAG, "generateDataLine: linearItems list is null ");
        }

        //点击显示数据组件
        XYMarkerView mv = new XYMarkerView(this, mIAxisValueFormatter_X);
        mv.setChartView(lineChart); // For bounds control
        lineChart.setMarker(mv); // Set the marker to the chart
    }

    private ArrayList<BarEntry> barEntriyList = new ArrayList<>();

    /**
     * generates a random ChartData object with just one DataSet
     */
    private void generateDataBar(List<LinearItem> linearItems, String nameGraph) {
        if (linearItems != null && linearItems.size() > 0) {
            LinearItem linearItem = linearItems.get(linearItems.size() - 1);
            if (linearItem != null) {
                List<Integer> data = linearItem.getData();
                has_K = false;
                ArrayList<BarEntry> entries = new ArrayList<>();
                //String[] split = AnalyzeStringUtil.getInstance().getStringArray(cnt);
                if (data != null && data.size() > 0) {
                    mMonthsValues = linearItems;
                    for (int i = 0; i < data.size(); i++) {
                        int i1 = data.get(i);
                        if (i1 > 1000) {
                            has_K = true;
                        }
                        entries.add(new BarEntry(i, i1));
                    }
                    barEntriyList.addAll(entries);
                    BarDataSet dSet;
                    if (barChart.getData() != null &&
                            barChart.getData().getDataSetCount() > 0) {
                        barChart.getXAxis().setAxisMinimum(0f);
                        barChart.getXAxis().setAxisMaximum(15f);
                        dSet = (BarDataSet) barChart.getData().getDataSetByIndex(0);
                        dSet.setValues(entries);
                        barChart.getData().notifyDataChanged();
                        barChart.notifyDataSetChanged();
                        Log.i(TAG, "generateDataBar: 走了柱状的数据缓存");
                        barChart.invalidate();
                    } else {
                        dSet = new BarDataSet(entries, nameGraph);
                        dSet.setColors(ColorTemplate.VORDIPLOM_COLORS);
                        dSet.setHighLightAlpha(255);
                        dSet.setDrawValues(false);
                        //设置点击后的透明度 数值是0~99;
                        dSet.setHighLightAlpha(37);

                        BarData cd = new BarData(dSet);
                        cd.setBarWidth(0.9f);
                        cd.setValueTextSize(10f);
                        // set data
                        barChart.setData(cd);
                        //需要在设置数据源后生效
                        //barChart.setVisibleXRangeMaximum(8);
                        Log.i(TAG, "generateDataBar: 柱状图没有数据缓存");
                    }

                } else {
                    Log.i(TAG, "generateDataBar: data is null");
                }
            }
        } else {
            Log.i(TAG, "generateDataBar: linearItems list is null");
        }
    }

    private ArrayList<PieEntry> entries_pie;

    private void generateDataPie(List<LinearItem> linearItems) {

        entries_pie = new ArrayList<PieEntry>();
        // NOTE: The order of the entries when being added to the entries array determines their position around the center of
        // the chart.
        if (linearItems != null && linearItems.size() > 0) {
            mMonthsValues = linearItems;
            for (int i = 0; i < linearItems.size(); i++) {
                LinearItem linearItem = linearItems.get(i);
                entries_pie.add(new PieEntry((float) linearItem.getYAxis(), linearItem.getName()));
            }
            PieDataSet dataSet = new PieDataSet(entries_pie, /*nameGraph*/"");
            dataSet.setSliceSpace(3f);
            dataSet.setSelectionShift(5f);
            // add a lot of colors
            ArrayList<Integer> colors = new ArrayList<Integer>();
            for (int c : ColorTemplate.VORDIPLOM_COLORS)
                colors.add(c);

            for (int c : ColorTemplate.JOYFUL_COLORS)
                colors.add(c);

            for (int c : ColorTemplate.COLORFUL_COLORS)
                colors.add(c);

            for (int c : ColorTemplate.LIBERTY_COLORS)
                colors.add(c);

            for (int c : ColorTemplate.PASTEL_COLORS)
                colors.add(c);

            colors.add(ColorTemplate.getHoloBlue());
            dataSet.setColors(colors);
            //dataSet.setSelectionShift(0f);

            dataSet.setValueLinePart1OffsetPercentage(80.f);
            //设置每个扇形数值上黑线的长度
            dataSet.setValueLinePart1Length(0.5f);
            dataSet.setValueLinePart2Length(0.5f);
            //dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
            dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);

            PieData data = new PieData(dataSet);
            Log.i(TAG, "generateDataPie:   " + entries_pie);
            //设置百分比显示
            data.setValueFormatter(new PercentFormatter(entries_pie));
            data.setValueTextSize(8f);
            data.setValueTextColor(Color.BLACK);
            pieChart.setData(data);

            // undo all highlights
            pieChart.highlightValues(null);
            pieChart.invalidate();
        }
    }

    private List<LinearItem> popWindPieList = new ArrayList<>();

    private List<LinearItem> getManagePieDate(List<LinearItem> linearItems) {
        popWindPieList.clear();
        float mil = getMil(linearItems);
        int num = 0;
        List<LinearItem> list = new ArrayList<>();
        if (linearItems != null && linearItems.size() > 0) {
            LinearItem linearItem = null;
            for (int i = 0; i < linearItems.size(); i++) {
                linearItem = linearItems.get(i);
                int yAxis = linearItem.getYAxis();
                if (yAxis <= mil) {
                    num = yAxis + num;
                    popWindPieList.add(linearItem);
                } else {
                    list.add(linearItem);
                }
            }
            LinearItem item = new LinearItem();
            item.setName("其他");
            if (num > mil) {
                item.setYAxis(num);
                list.add(item);
            } else {
                if (num > 0) {
                    item.setYAxis((int) mil);
                    item.setName("其他");
                    item.setType("@" + num);
                    list.add(item);
                }
            }
        }
        return list;
    }

    /**
     * 是否重置折线图
     **/
    private void isResetClickLineChart() {
        if (lineChart != null) {
            //把隐藏的折线图显示出来
            if (mapEntry != null && mapEntry.size() > 0) {
                for (int i = 0; i < mapEntry.size(); i++) {
                    setLineVisible(i, true);
                }
            }
            lineChart.animateY(3000);
            lineChart.fitScreen();
        } else {
            Log.i(TAG, "isResetClickLineChart: lineChart is null");
        }
    }

    /**
     * 折线的显示和隐藏
     **/
    private void setLineVisible(int number, boolean isShow) {
        if (lineChart != null) {
            LineDataSet set2 = (LineDataSet) lineChart.getData().getDataSetByIndex(number);
            if (set2 != null) {
                set2.setVisible(isShow);
            }
            lineChart.invalidate();
        }

    }

    private int getLevelByName(List<Level> data, String name) {
        int l = 0;
        Level level = null;
        for (int i = 0; i < data.size(); i++) {
            level = data.get(i);
            if (level.getName().equals(name)) {
                l = level.getLevel();
                break;
            }
        }
        return l;
    }

    /**
     * 获取百分之一值
     */
    private float getMil(List<LinearItem> linearItems) {
        float num = 0;
        if (linearItems != null && linearItems.size() > 0) {
            for (int i = 0; i < linearItems.size(); i++) {
                LinearItem linearItem = linearItems.get(i);
                int yAxis = linearItem.getYAxis();
                num = yAxis + num;
            }
        }
        Log.i(TAG, "getMil   num: " + num + "  千分之一 ： " + num / 100);
        return num / 100;
    }

    private PieOtherAnalyzeBoard mPieOtherAnalyzeBoard;

    /**
     * 显示饼状图中的其他项
     *
     * @param childPosition
     */
    private void showPieOther(int childPosition) {
        if (entries_pie != null && entries_pie.size() > 0) {
            if (entries_pie.size() - 1 == childPosition) {
                if (mPieOtherAnalyzeBoard != null && mPieOtherAnalyzeBoard.isShowing()) {
                    mPieOtherAnalyzeBoard.dismiss();
                }
                //初始化popWindow
                mPieOtherAnalyzeBoard = new PieOtherAnalyzeBoard(mContext, popWindPieList);
                mPieOtherAnalyzeBoard.showAtLocation(TrendAuthDayActivity.this.getWindow().getDecorView(), Gravity.CENTER, 0, 0);
                mPieOtherAnalyzeBoard.setOutsideTouchable(true);  //设置点击屏幕其它地方弹出框消失
            }
        }
    }

    /**
     * 判断二级列表是否全部展开
     **/
    private boolean isGroupExpanded() {
        boolean isOpen = false;
        if (trendAuthDataExpandable != null) {
            if (mMonthsValues != null && mMonthsValues.size() > 0) {
                for (int i = 0; i < mMonthsValues.size(); i++) {
                    if (!trendAuthDataExpandable.isGroupExpanded(i)) {
                        Log.i(TAG, "isGroupExpanded   : " + i);
                        isOpen = true;
                    } else {
                        return false;
                    }
                }
            }
        }
        return isOpen;
    }

    /**
     * 转换X轴倒序
     */
    private List<String> setInvertedOrderXForGraph(List<String> xForGraph) {
        String iconType = AnalyzeIntentUtil.getInstance(mContext).getIconType();
        Log.i(TAG, "setInvertedOrderXForGraph    iconType: " + iconType);
        if (iconType.equals(AnalyzeIntentUtil.LINAR_CHART)) {
            List<String> mXForGraph = new ArrayList<>();
            for (int i = xForGraph.size() - 1; i >= 0; i--) {
                mXForGraph.add(xForGraph.get(i));
            }
            return mXForGraph;
        }
        return xForGraph;
    }

    /**
     * 转换Y轴倒序
     */
    private List<LinearItem> setInvertedOrderYForGraph(List<LinearItem> monthsValues) {
        String iconType = AnalyzeIntentUtil.getInstance(mContext).getIconType();
        Log.i(TAG, "setInvertedOrderYForGraph    iconType: " + iconType);
        if (iconType.equals(AnalyzeIntentUtil.LINAR_CHART)) {
            Log.i(TAG, "setInvertedOrderYForGraph  hou :   " + AnalyzeIntentUtil.LINAR_CHART);
            List<Integer> datas = null;
            for (int i = 0; i < monthsValues.size(); i++) {
                LinearItem linearItem = monthsValues.get(i);
                List<Integer> data = linearItem.getData();
                datas = new ArrayList<>();
                for (int s = data.size() - 1; s >= 0; s--) {
                    datas.add(data.get(s));
                }
//                Collections.reverse(data);
                linearItem.setData(data);
            }
            return monthsValues;
        }
        return monthsValues;
    }
}
